// pages/Orders/SubmitOrder/SubmitOrder.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { getAddress , getUserAccount , getGoodsCouponInfo , checkUserPassword , queryUserWechatOpenId , getUser , updateUser } from '../../../api/user';
import { caclulateGoodsOrderPrice , goodsOrderSubmit , goodsOrderPay } from '../../../api/order';
import { getChannel } from '../../../api/brand';
import { checkUserPasswordIsSet } from '../../../api/login';
const regeneratorRuntime = require('../../../common/runtime');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareTitle: app.globalData.global.shareTitle,
    assetsAddress: assetsAddress,
    address: {},
    goodsCard: [], // 结算商品列表
    remarks: '', // 订单备注
    balance: 0, // 余额
    integral: 0, // 积分
    coupons: [], // 可使用优惠券列表
    couponId: '', // 优惠券ID
    channel: [], // 支付渠道
    payType: [1], // 支付方式Type
    price: 0, // 商品订单支付金额
    totalFreight: 0, // 运费
    totalPrice: 0, // 商品总价
    paddingBtm: 0,
    noDistribution: false,
    showCoupon: false,
    unionid: '',
    payPassword: '', // 支付密码
    shopName: '', // 花店名称
    showSetShopName: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.item){
      console.log(JSON.parse(options.item),'item')
      this.setData({
        goodsCard: JSON.parse(options.item)
      })
    }
    // this._getUserAccount(5);
    // this._getChannel();
    this._queryUserWechatUnionId();
    const res = wx.getSystemInfoSync()
    const { screenHeight, safeArea: { bottom } } = res
    if (screenHeight && bottom){
      let safeBottom = screenHeight - bottom
      this.setData({
        paddingBtm: 50 + safeBottom
      })
    }else{
      this.setData({
        paddingBtm: 50
      })
    }
    this.getUser();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this._getAddress();
    this._getUserAccount('0');
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 获取用户收货地址
  _getAddress(){
    let _this = this;
    let userId = wx.getStorageSync('userId')
    let addressId = wx.getStorageSync('addressId') || '';
    getAddress({userId: userId, isDefault: '',id: addressId})
    .then(res => {
      if(res.success){
        if(res.data.length > 0){
          var ads = res.data.find(item => {
            return item.isDefault == '1'
          })
          if(!ads){
            ads = res.data[0];
          }
          _this.setData({
            address: ads,
          })
          wx.setStorageSync('addressId','');
          wx.setStorageSync('province', ads.province)
          wx.setStorageSync('city', ads.province)
          wx.setStorageSync('country', ads.area)
          _this._getGoodsCouponInfo();
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取用户账户余额
  _getUserAccount(type){
    let _this = this;
    getUserAccount(type)
    .then(res => {
      if(res.success){
        if(type == 0){
          _this.setData({
            balance : res.data.balance,
            payType: res.data.balance > 0 ? [1] : []
          })
        }else if(type == 5){
          _this.setData({
            integral : res.data.balance,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
  // 获取用户优惠券
  _getGoodsCouponInfo(){
    let _this = this;
    getGoodsCouponInfo({status: '0',size: 99})
    .then(res => {
      if(res.success){
        var amount = 0;
        for (let index = 0; index < _this.data.goodsCard.length; index++) {
          const item = _this.data.goodsCard[index];
          console.log(item,'Youhuiquan');
          if(item.merchantId == '0'){
            amount += item.addToCartPrice * item.quantity;
          }
        }
        var list = []
        var couponId = ''
        for (let index = 0; index < res.data.content.length; index++) {
          const item = res.data.content[index];
          if(item.requirement <= amount){
            couponId = item.id;
          }
          list.push(item);
        }
        _this.setData({
          coupons: [{id: '',name: '不使用优惠券'},...list],
          couponId: couponId,
          orderAmount: amount,
        })
        _this._getGoodsOrderPrice();
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取通道配置信息
  _getChannel(){
    let _this = this;
    getChannel({})
    .then(res => {
      if(res.success){
        var list = [];
        var payType = JSON.parse(JSON.stringify(_this.data.payType))
        for (let index = 0; index < res.data.content.length; index++) {
          const item = res.data.content[index];
          if((item.channelName.indexOf('微信') != -1 && item.channelName.indexOf('支付') != -1)){
            list.push(item);
            // payType.push(item.payType)
          }
        }
        _this.setData({
          channel: list,
          // payType: payType,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 切换支付渠道
  selPayType(e){
    console.log(e);
    let payType = e.target.dataset.type||e.currentTarget.dataset.type;
    // this.setData({
    //   payType: [payType],
    // })
    var arr = this.data.payType;
    console.log(arr,'arr')
    console.log(arr.indexOf(payType))
    if(arr.indexOf(payType) != -1){
      arr.splice(arr.indexOf(payType),1)
      console.log(arr,'arr')
      this.setData({
        payType: arr,
      })
    }else{
      arr.push(payType);
      this.setData({
        payType: arr,
      })
    }
  },
  // 是否选择余额支付
  selBalancePay(){
    // this.setData({
    //       payType: [1],
    // })
    if(this.data.balance == 0){
      return;
    }
    var arr = this.data.payType;
    console.log(arr,'arr')
    console.log(arr.indexOf(1))
    if(arr.indexOf(1) != -1){
      arr.splice(arr.indexOf(1),1)
      console.log(arr,'arr')
      this.setData({
        payType: arr,
      })
    }else{
      arr.push(1);
      this.setData({
        payType: arr,
      })
    }
  },
  // 修改商品数量
  quantityChange(e){
    console.log(e,'e')
    let _this = this;
    let index = e.target.dataset.index||e.currentTarget.dataset.index;
    this.data.goodsCard[index].quantity = e.detail;
    console.log(this.data.goodsCard,'goodsCard')
    var amount = 0;
    for (let index = 0; index < _this.data.goodsCard.length; index++) {
      const item = _this.data.goodsCard[index];
      console.log(item,'Youhuiquan');
      if(item.merchantId == '0'){
        amount += item.addToCartPrice * item.quantity;
      }
    }
    this.setData({
      orderAmount: amount,
      couponId: '',
    })
    this._getGoodsOrderPrice();
  },
  // 计算商品价格
  _getGoodsOrderPrice(){
    let _this = this;
    if(!_this.data.address.id){
      wx.showToast({
        title: '请先添加收货地址后，再进行操作！',
        icon: 'none',
      })
      return;
    }
    caclulateGoodsOrderPrice({specInfo: JSON.stringify(_this.data.goodsCard),receiveAddressId: _this.data.address.id,couponId: _this.data.couponId})
    .then(res => {
      if(res.success){
        // if(res.data.balanceIsEnough == '0'){
        //   var payType = _this.data.payType;
        //   if(payType.indexOf(3) == -1){
        //     payType.push(3);
        //     console.log(payType,'paytype')
        //     _this.setData({
        //       payType: payType,
        //     })
        //   }
        // }
        _this.setData({
          price: res.data.payAmount > 0 ? res.data.payAmount : 0,
          totalFreight: res.data.totalFreight,
          totalPrice: res.data.totalPrice,
          noDistribution: false,
        })
      }else{
        if(res.errMessage == '当前地区暂未开通配送服务！'){
          _this.setData({
            noDistribution: true,
          })
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      }
    })
  },
  // 确认下单
  async onSubmit(){
    let _this = this;
    console.log(_this.data.payType,'payType')
    if(!_this.data.address.id){
      wx.showModal({
        title: '温馨提示',
        content: '您还未添加收货地址，请先添加地址',
        success: () => {
          wx.navigateTo({
            url: '/pages/Users/MyAddress/MyAddress',
          })
        }
      })
    }else{
      var isOneStore = true;
      var oneStore = _this.data.goodsCard[0].storehouseId;
      for (let index = 0; index < _this.data.goodsCard.length; index++) {
        const item = _this.data.goodsCard[index];
        if(oneStore != item.storehouseId){
          isOneStore = false
        }
      }
      if(!isOneStore){
        wx.showToast({
          title: '当前商品里面的发货地不一致，请更换商品后再进行操作！',
          icon: 'none'
        })
        return;
      }
      if(_this.data.shopName == '' || _this.data.shopName == null){
        _this.setData({
          showSetShopName: true,
        });
        return;
      }
      if(_this.data.payType == ''){
        wx.showToast({
          title: '请先选择支付方式！',
          icon: 'none'
        })
        return;
      }
      if(_this.data.payType.indexOf(1) != -1){
        if(_this.data.price > _this.data.balance && _this.data.payType.length == 1){
          wx.showModal({
            title: '温馨提示',
            content: '当前余额不足，是否前往充值？',
            success: (modal) =>{
              if(modal.confirm){
                wx.navigateTo({
                  url: '/pages/Users/UpTopBalance/UpTopBalance',
                })
              }
            },
          })
        }else{
          const isSetPayPassword = await _this._checkUserPasswordIsSet();
          if(!isSetPayPassword){
            var phone = wx.getStorageSync('phone');
            if(phone.length != 11){
              wx.showModal({
                title: '温馨提示',
                content: '当前暂未设置交易密码，设置交易密码之前需要绑定手机号，是否前往绑定？',
                success: (modal) =>{
                  if(modal.confirm){
                    wx.navigateTo({
                      url: '/pages/Users/BindPhone/BindPhone',
                    })
                  }
                },
              })
              return;
            }
            wx.showModal({
              title: '温馨提示',
              content: '暂未设置交易密码，是否前往设置？',
              success: (modal) =>{
                if(modal.confirm){
                  wx.navigateTo({
                    url: '/pages/Users/UpdatePayPassword/UpdatePayPassword',
                  })
                }
              },
            })
            return;
          }
          const child = _this.selectComponent('.pay-passwordAuth');
          console.log(child,'child')
          child.clearPassword();
          child.openPayAuth();
        }
      }else{
        _this._submitOrder();
      }
      // if(_this.data.payType.indexOf(1) != -1){
      //   if(_this.data.payType.length == 1 && _this.data.price > _this.data.balance){
      //     wx.showToast({
      //       title: '当前余额不足，请更换其他支付方式，或者组合支付',
      //       icon: 'none'
      //     })
      //     return;
      //   }
      //   const isSetPayPassword = await _this._checkUserPasswordIsSet();
      //   if(!isSetPayPassword){
      //     var phone = wx.getStorageSync('phone');
      //     if(phone.length != 11){
      //       wx.showModal({
      //         title: '温馨提示',
      //         content: '当前暂未设置交易密码，设置交易密码之前需要绑定手机号，是否前往绑定？',
      //         success: (modal) =>{
      //           if(modal.confirm){
      //             wx.navigateTo({
      //               url: '/pages/Users/BindPhone/BindPhone',
      //             })
      //           }
      //         },
      //       })
      //       return;
      //     }
      //     wx.showModal({
      //       title: '温馨提示',
      //       content: '暂未设置交易密码，是否前往设置？',
      //       success: (modal) =>{
      //         if(modal.confirm){
      //           wx.navigateTo({
      //             url: '/pages/Users/UpdatePayPassword/UpdatePayPassword',
      //           })
      //         }
      //       },
      //     })
      //     return;
      //   }
      //   const child = _this.selectComponent('.pay-passwordAuth');
      //   console.log(child,'child')
      //   child.clearPassword();
      //   child.openPayAuth();
      // }else{
      //   _this._submitOrder();
      // }
    }
  },
  // 余额支付校验密码成功
  sonSubmitOrder(e){
    console.log(e,'e')
    this.setData({
      payPassword: e.detail,
    })
    this._submitOrder();
  },
  // 下单
  _submitOrder(){
    let _this = this;
    goodsOrderSubmit({receiveAddressId: _this.data.address.id,couponId: _this.data.couponId,specInfo: JSON.stringify(_this.data.goodsCard),remarks: _this.data.remarks})
      .then(res => {
        if(res.success){
          _this.pay({orderCode:res.data.orderCode,payType:_this.data.payType.indexOf(1) != -1 ? 1 : _this.data.payType[0],amount: _this.data.payType.length > 1 ? _this.data.balance > _this.data.price ? _this.data.price : _this.data.balance : ''})
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
  },
  pay({orderCode,payType,amount}){
    let _this = this;
    goodsOrderPay({isAllPay: '1',payType: payType,orderCode: orderCode,openId: _this.data.unionid,isMixPay: _this.data.payType.length > 1 ? '1' : '0',payAmount: amount,payPassword: payType == '1' ? _this.data.payPassword : null}).then(res => {
      if(res.success){
        _this.wechatPay({orderCode: orderCode,payType: payType,wechatSign: res.data});
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 支付
  wechatPay({orderCode,payType,wechatSign}){
    let _this = this;
    if(_this.data.payType.indexOf(1) != -1 && payType == 1){
      if(_this.data.payType.length == 1 || _this.data.balance > _this.data.price || _this.data.balance == _this.data.price){
        wx.navigateTo({
          url: '/pages/Orders/PaySuccess/PaySuccess',
        })
      }else{
        // 组合支付
        var arr = JSON.parse(JSON.stringify(_this.data.payType));
        arr.splice(arr.indexOf(1),1);
        _this.pay({orderCode: orderCode,payType: arr[0],amount: _this.data.price - _this.data.balance})
      }
    }else{
      // console.log(JSON.parse(wechatSign),'jsonData');
      var order = JSON.parse(wechatSign)
      // TODO微信支付
      wx.requestPayment({
        timeStamp: order.timeStamp.toString(),
        nonceStr: order.nonceStr,
        package: order.package,
        signType: order.signType,
        paySign: order.paySign,
        success: () => {
          wx.navigateTo({
            url: '/pages/Orders/PaySuccess/PaySuccess',
          })
        },
        fail: (err) => {
          console.log(err,'err')
          wx.showToast({
            title: '取消支付',
            icon: 'none',
          })
        }
      })
    }
  },
  // 页面跳转
  goNext(e){
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    if(url == '/pages/Users/MyAddress/MyAddress'){
      wx.setStorageSync('isMyAddressPop', '1')
    }
    // return
    if(item){
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}?item=${JSON.stringify(item)}`,
        })
      }
    }else{
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}`,
        })
      }
      
    }
  },
  // 展示选择优惠券选择框
  showCoupons(){
    this.setData({
      showCoupon: true,
    })
  },
  // 关闭优惠券选择框
  showCouponClose(){
    this.setData({ showCoupon: false });
  },
  // 选择优惠券
  selCoupon(e){
    let _this = this;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    if(item.requirement > _this.data.orderAmount){
      return;
    }
    this.setData({
      couponId: item.id,
      showCoupon: false,
    })
    this._getGoodsOrderPrice()
  },
  // 校验是否设置过支付密码
  _checkUserPasswordIsSet(){
    let _this = this;
    return new Promise((resolve,reject) => {
      checkUserPasswordIsSet({})
      .then(res => {
        if(res.success){
          resolve(true)
        }else{
          resolve(false)
        }
      })
    })
  },
  // 获取用户的Openid
  _queryUserWechatUnionId(){
    let _this = this;
    wx.login({
      success: (logRes) => {
        queryUserWechatOpenId({code: logRes.code})
        .then(res => {
          if(res.success){
            _this.setData({
              unionid: res.data.openid
            })
          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
      }
    })
  },
  // 获取用户个人信息
  getUser(){
    let _this = this;
    getUser()
    .then(res => {
      if(res.success){
        _this.setData({
          shopName: res.data.shopName,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 设置花店名称
  setShopName(){
    let _this = this;

  },
  onClose(){
    this.setData({
      showSetShopName: false,
    })
  },
  confirm(){
    let _this = this;
    updateUser({shopName: _this.data.shopName,})
    .then(res => {
      if(res.success){
        _this.getUser();
        wx.setStorageSync('hasUpdateUser', '1')
        wx.showToast({
          title: '设置成功',
          icon: 'success',
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
})